package com.aceitunaproject.shared.message;

import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Logger;

import com.aceitunaproject.shared.util.BinaryObjectSerializer;
import com.aceitunaproject.shared.util.ObjectSerializer;

/**
 * @author Federico Bergstein
 * 
 *         Default implementation of the MessageSender Interface
 */
public class MessageSenderImpl implements MessageSender {

	private final static Logger logger= Logger.getLogger(MessageSenderImpl.class.toString());
	
	private AceitunaSender sender;

	/**
	 * 
	 * @param mySender
	 */
	public MessageSenderImpl(AceitunaSender mySender) {
		this.sender = mySender;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.aceitunaproject.shared.util.MessageSender#sendMessage(com.aceitunaproject
	 * .shared.message.Message)
	 */
	public void sendMessage(Message message) {

		if (message == null)
			throw new NullPointerException("Null message");

		message.setId(UUID.randomUUID().toString());
		message.setTimeStamp(new Date());

		// TODO: using the default implementation of perhaps it should be a
		// parameter like the AceitunaSender?
		ObjectSerializer serializer = new BinaryObjectSerializer();
		byte[] serializedObject = serializer.serialize(message);

		ByteBuffer msg = ByteBuffer.allocate(1 + serializedObject.length);
		msg.put(MessageConstants.TYPE_OBJECT);
		msg.put(serializedObject);
		msg.flip();
		this.sender.sendMessage(msg);

		logger.info("message id " + message.getId() + " sent" + message.getTimeStamp().toString());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.aceitunaproject.shared.util.MessageSender#setDarkstarSender(com.
	 * aceitunaproject.shared.util.DarkStarSender)
	 */
	public void setDarkstarSender(AceitunaSender mySender) {
		this.sender = mySender;
	}

}
